<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<%@ include file="/common/mainhead.html" %>
<script>
	var frameStr = "window.frames['toUserManager']";
	
	//----------------------------------------------------Combobox初始化
	$(function(){
		$('#comb_isStoped').combobox({
		    url:'getIsStopedStateWithEmpty.do',
		    valueField:'key',
		    textField:'value',
		    value:'0'
		});
	});

		
	//----------------------------------------------------DataGrid初始化	
    function dgLoadSuccess(data){
        $(".acteditbutton").linkbutton({ text: "编辑", plain: true, iconCls: "icon-edit" });
        $(".unacteditbutton").linkbutton({ text: "编辑", plain: true, iconCls: "icon-edit", disabled: true });
        $(".stopbutton").linkbutton({ text: "停用", plain: true, iconCls: "icon-no" });
        $(".restorebutton").linkbutton({ text: "恢复", plain: true, iconCls: "icon-ok" });
        $(".removebutton").linkbutton({ text: "删除", plain: true, iconCls: "icon-remove" });
    }
	
	function dgRowStyle(index, row){
        if (row.isStoped) {
            return 'background-color:#fbcdcd;';
        } 
	}
	
	//----------------------------------------------------状态字段格式化
    
    function formatDelete(value,row,index){
		return '<a class="removebutton" onclick="deleteItem(\'' + row.id + '\',\'' + row.userName + '\')"></a>';
    }
    
    function formatEdit(value,row,index){
        if (row && row.isStoped != null) {
            if (!row.isStoped) {
                return '<a class="acteditbutton" onclick="showWindow(false, \'' + row.id + '\')"></a>';
            } else {
                return '<a class="unacteditbutton" onclick="javascript:void(0)"></a>';
            }
        }
    }
    
    function formatStoped(value,row,index){
        if (row && row.isStoped != null) {
            if (!row.isStoped) {//未停用
                return '<a class="stopbutton" onclick="stopUser(\'' + row.id + '\',' + row.isStoped+ ',\'' + row.userName + '\')"></a>';
            } else {//已停用
                return '<a class="restorebutton" onclick="stopUser(\'' + row.id + '\',' + row.isStoped + ')"></a>';
            }
        }
    }
    
    function formatState(value,row,index){
        if (row && row.isStoped != null) {
            if (!row.isStoped) {//未停用
                return UNSTOPED;
            } else {//已停用
                return STOPED;
            }
        }
    }
    
    function formatRole(value,row,index){
    	return '<a href="javascript:void(0)" onclick="showRoleWin(\'' + row.id + '\',\'' + row.userName + '\')">角色</a>'; 
    }
    
    
    //------------------------------------------------------------------------------------操作
    
    function query(){
    	var isValid = top$("#form_query").form("validate");
    	if(isValid){
        	var queryParams = $('#dg').datagrid('options').queryParams;
        	queryParams.kssj = $('#date_start').datebox('getValue');
        	queryParams.jssj = $('#date_end').datebox('getValue');
        	queryParams.realName = $('#txt_realName').val();
        	queryParams.isStoped = $('#comb_isStoped').combobox('getValue');
        	$('#dg').datagrid('options').queryParams = queryParams;
        	$("#dg").datagrid('load');
    	}
    }
    
    //停用/恢复
    function stopUser(id, isStoped, userName){
    	var adminUserName = $('#hide_admin_user').val();
    	if(userName && userName == adminUserName){
    		top$.messageBox5s('无法停用管理员用户');
    	}else{
        	top$.messager.confirm('系统提示',isStoped ? "确定恢复用户吗？" : "确定停止用户吗？", function(r){
        		if(r){
        	        $.post("stopOneUser.do",{id:id,isStoped:isStoped},function(data){
        	        	if(data.flag == JSON_FLAG_SUCCESS){
        	    			$('#dg').datagrid('reload');
        	    			top$.messageBox5s(OPT_SUCCESS);
        	    		}else{
        	    			top$.messageBox5s(OPT_FAIL + ':' + data.errmsg);
        	    		}     
        	        });
        		}   		
        	});
    	}
    }
    
    //删除
    function deleteItem(id, userName){
    	var adminUserName = $('#hide_admin_user').val();
    	if(userName != adminUserName){
        	top$.messager.confirm('系统提示',"确定删除用户信息吗？", function(r){
        		if(r){
                    $.post("deleteOneUser.do",{id:id},function(data){
                    	if(data.flag == JSON_FLAG_SUCCESS){
                			$('#dg').datagrid('reload');
                			top$.messageBox5s(DEL_SUCCESS);
                		}else{
                			top$.messageBox5s(DEL_FAIL + ':' + data.errmsg);
                		}     
                    });
        		}    		
        	});
    	}else{
    		top$.messageBox5s('无法删除管理员用户');
    	}
    }
    
    function showWindow(isAdd, id){
    	var dialogId = 'myDialogId';
    	var title = isAdd?'新增':'修改';
    	var okFunc = isAdd?'addItem()':'editItem(\''+ id +'\')';
    	var options ="buttons: [{text:'确定',iconCls:'icon-ok',handler:function(){"+frameStr+"."+ okFunc +"}},{text:'取消',iconCls:'icon-cancel',handler:function(){$('#"+ dialogId +"').dialog('close')}}]";
		var content = $('#dialog_content').html().replaceAll('e-validatebox','easyui-validatebox');
		openFrameDialog(dialogId, title, 800, 150, content, options);
		if (!isAdd) {
			$.ajax({
				url : 'getOneUserById.do',
				async : false,
				type : "POST",
				dataType : "json",
				data : {id:id},
				success : function(data) {
					if (data.flag == JSON_FLAG_SUCCESS) {
						top$('#win_txt_userName').val(data.userName);
						top$('#win_txt_realName').val(data.realName);
						top$('#win_txt_email').val(data.userEmail);
						top$('#win_txt_phoneNumber').val(data.phoneNumber);
						top$("#form1").form("validate");
						top$('#win_txt_userName').attr('disabled',true);
					} else {
						top$.messageBox5s(ERROR_ITEMMISS);
						return;
					}
				}
			});
		}
	}

	function addItem() {
		var isValid = top$("#form1").form("validate");
		if (isValid) {
			top$.messager.progress();
			var userName = top$('#win_txt_userName').val();
			var realName = top$('#win_txt_realName').val();
			var email = top$('#win_txt_email').val();
			var phoneNumber = top$('#win_txt_phoneNumber').val();
			$.post('addOneUser.do', {
				userName : userName,
				realName : realName,
				email : email,
				phoneNumber:phoneNumber
			}, function(data) {
				top$.messager.progress('close');
				if (data.flag == JSON_FLAG_SUCCESS) {
					$('#dg').datagrid('reload');
					top$('#myDialogId').dialog('close');
					top$.messageBox5s(ADD_SUCCESS);
				} else {
					top$.messageBox5s(ADD_FAIL + ':' + data.errmsg);
				}
			});
		}
	}

	function editItem(id) {
		var isValid = top$("#form1").form("validate");
		if (isValid) {
			top$.messager.progress();
			var realName = top$('#win_txt_realName').val();
			var email = top$('#win_txt_email').val();
			var phoneNumber = top$('#win_txt_phoneNumber').val(); 
			$.post('editOneUser.do', {
				id:id,
				realName:realName,
				email:email,
				phoneNumber:phoneNumber
			}, function(data) {
				top$.messager.progress('close');
				if (data.flag == JSON_FLAG_SUCCESS) {
					$('#dg').datagrid('reload');
					top$('#myDialogId').dialog('close');
					top$.messageBox5s(EDIT_SUCCESS);
				} else {
					top$.messageBox5s(EDIT_FAIL + ':' + data.errmsg);
				}
			});
		}
	}
	
	//打开角色窗口
	function showRoleWin(id, userName){
		var adminUserName = $('#hide_admin_user').val();
		if(userName == adminUserName){
    		top$.messageBox5s('无法为管理员用户分配角色');
    	}else{
    		var dialogId = 'myDialogId';
    		var title = "角色分配";
    		var options ="buttons: [{text:'确定',iconCls:'icon-ok',handler:function(){"+frameStr+".editRoleTree(\'"+id+"\')}}]";
    		var content = $('#dialog_roletree_content').html();
    		openFrameDialog(dialogId, title, 400, 360, content, options);
    	  	top$('#tree_role').tree({
    	 		checkbox:true,
    	 		lines:true,
    			url:'getRoleTreeByUserId.do?userId='+id,
    			onLoadSuccess:function(node,data){
    				var t = top$(this);
    				if(data){
    					top$(data).each(function(index,d){  
    						if(this.state == 'closed'){
    						    t.tree('expandAll');
    						   }					
    					})
    				}			
    			}
    		});
    	}
	}

	//设置角色
	function editRoleTree(id){
		var nodes =  top$('#tree_role').tree('getChecked');
		var s = '';
	 	top$(nodes).each(function(index, item){
			if( s != '' ) s+= normalFlag;
			s += item.id;
		})
	 	$.post('saveUserRoleForUser.do',{userId:id,roleIds:s},function(data){
	    	if(data.flag == JSON_FLAG_SUCCESS){
	    		top$('#myDialogId').dialog('close');
				top$.messageBox5s(OPT_SUCCESS);
			}else{
				top$.messageBox5s(OPT_FAIL + ':' + data.errmsg);
			}    
		});
	}
</script>
</head>
<body>
<div id="toolbar" style="padding:3px;height:25px;">
	<span style="float:left;">
		<a href="javascript:void(0)" onclick="showWindow(true);" class="easyui-linkbutton" iconCls="icon-add" plain="true">新增</a>
	</span>
	<span style="float:right;margin-right:30px;">
		<form id="form_query">
			<span>日期:</span>
			<input class="easyui-datebox" id="date_start" data-options="validType:'date'" style="width:120px" />
			<span>至: </span>
			<input class="easyui-datebox" id="date_end" data-options="validType:['date','dateValid[\'#date_start\']']" style="width:120px" />
			<span>姓名:</span>
			<input class="easyui-textbox" id="txt_realName" style="width:120px;"></input>
			<span>状态:</span>
			<input class="easyui-combobox" editable="false" id="comb_isStoped" style="width:120px;"></input>
			<a href="#" class="easyui-linkbutton" onclick="query()" iconCls="icon-search" >查询</a>
		</form>
	</span>

</div>            
<div id="div_main">
<table id="dg" class="easyui-datagrid"
	data-options="url:'getUsersInPage.do',width:'100%',height:'100%',rownumbers:true,loadMsg:'数据加载中，请稍后......',
	singleSelect:true,pagination:true,pageSize:20,pageList: [20, 50, 100],toolbar:'#toolbar',method:'get',
	onLoadSuccess:dgLoadSuccess,rowStyler:dgRowStyle">
	<thead>
		<tr>
			<th data-options="field:'opt1',align:'center',formatter:formatDelete,width:60">删除</th>
			<th data-options="field:'opt2',align:'center',formatter:formatEdit,width:60">修改</th>
			<th data-options="field:'opt3',align:'center',formatter:formatStoped,width:60">停用/恢复</th>
			<th data-options="field:'opt4',align:'center',formatter:formatRole,width:'60'">角色</th>
			
			<th data-options="field:'userName',width:100">用户名</th>
			<th data-options="field:'realName',width:100">姓名</th>
			<th data-options="field:'userEmail',width:150">邮箱</th>
			<th data-options="field:'phoneNumber',width:100">手机号</th>
			<th data-options="field:'isStoped',formatter:formatState,width:80">状态</th>
			<th data-options="field:'creater',width:100">创建人</th>
			<th data-options="field:'createTime',width:150">创建时间</th>
			<th data-options="field:'updater',width:100">更新人</th>
			<th data-options="field:'updateTime',width:150">更新时间</th>
		</tr>	
	</thead>
</table>
</div>

<div id="dialog_content">
	<form id="form1" style="margin:15px 10px;">
		<table>
			<tbody>
				<tr>
					<td style="width:60px;">用户名</td>
					<td><input data-options="required:true,validType:'length[3,10]'" class="e-validatebox textbox" style="width:120px;" id="win_txt_userName"/></td>
					<td style="width:60px;">姓名</td>
					<td><input data-options="required:true,validType:'length[3,10]'" class="e-validatebox textbox" style="width:120px;" id="win_txt_realName"/></td>
					<td style="width:60px;">邮箱</td>
					<td><input data-options="required:false,validType:'email'" class="e-validatebox textbox" style="width:120px;" id="win_txt_email"/></td>
					<td style="width:60px;">手机号</td>
					<td><input data-options="required:false,validType:'mobile'" class="e-validatebox textbox" style="width:120px;" id="win_txt_phoneNumber"/></td>
				</tr>
			</tbody>
		</table>	
	</form>
</div>
<div id="dialog_roletree_content">
	<ul id="tree_role">
	</ul>
</div>
<input id="hide_admin_user" type="hidden" value="${userkey}" /> 
</body>
</html>